<template>
  <div class="container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="header-title">指挥调度可视化大屏</div>
      <div class="header-time">{{ currentTime }}</div>
    </div>

    <!-- 左一：实时警情 -->
    <div class="panel incident-list">
      <div class="panel-title">实时警情</div>
      <div class="panel-content scrollable" ref="incidentListScroll">
        <div class="incident-item" v-for="incident in incidents" :key="incident.incidentId">
          <div class="incident-header">
            <span class="incident-title">{{ incident.incidentType }}</span>
            <span class="incident-time">{{ incident.reportTime }}</span>
          </div>
          <div class="incident-desc">{{ incident.description }}</div>
        </div>
      </div>
    </div>

    <!-- 左二：警力监控 -->
    <div class="panel police-force">
      <div class="panel-title">警力监控</div>
      <div class="panel-content scrollable" ref="policeForceScroll">
        <div class="scroll-container">
          <div class="force-item" v-for="force in policeForces" :key="force.officerId">
            <div class="force-icon" v-html="force.icon || '&#128110;'"></div>
            <div class="force-info">
              <div class="force-name">{{ force.name }}</div>
              <div class="force-status" :class="`status-${force.statusDescription}`">{{ force.statusDescription }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 左三：调度控制台 -->
<!--    <div class="panel dispatch-console">-->
<!--      <div class="panel-title">调度控制台</div>-->
<!--      <div class="panel-content">-->
<!--        <div class="console-messages scrollable" ref="consoleMessagesScroll">-->
<!--          <div class="console-message" v-for="message in consoleMessages" :key="message.id">-->
<!--            <span class="message-time">{{ message.time }}</span>-->
<!--            <span class="message-content">{{ message.content }}</span>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

    <!-- 中间：主地图 -->
    <div class="panel main-map">
      <div class="panel-title">警力分布与警情热力图</div>
      <div class="map-container" id="main-map-container">
      </div>
    </div>

    <!-- 右一：统计图表 -->
    <div class="panel statistics">
      <div class="panel-title">警情趋势分析</div>
      <div class="chart-container" id="trend-chart-container">
      </div>
    </div>

    <!-- 右二：关键指标 -->
    <div class="panel key-metrics">
      <div class="metric-card">
        <div class="metric-value">{{ todayIncidentsCount }}</div>
        <div class="metric-title">今日警情</div>
        <div class="metric-comparison" :class="getRateColor(todayIncidentsRate)">
          同比 {{ todayIncidentsRate > 0 ? '+' : '' }}{{ todayIncidentsRate }}%
        </div>
      </div>
      <div class="metric-card">
        <div class="metric-value">{{ onlinePolice }}/{{ totalPolice }}</div>
        <div class="metric-title">在职警力/总警力</div>
      </div>
      <div class="metric-card">
        <div class="metric-value">{{ averageResponseTime }} <span class="unit">分钟</span></div>
        <div class="metric-title">平均响应时间</div>
      </div>
      <div class="metric-card">
        <div class="metric-value">{{ incidentHandlingRate }}%</div>
        <div class="metric-title">警情处理率</div>
        <div class="metric-comparison" :class="getRateColor(incidentHandlingRateRate)">
          同比 {{ incidentHandlingRateRate > 0 ? '+' : '' }}{{ incidentHandlingRateRate }}%
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/utils/axios.js';
import * as echarts from 'echarts/core';
import { BarChart, LineChart, ScatterChart, EffectScatterChart, HeatmapChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, GeoComponent, VisualMapComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import 'echarts-extension-amap';

echarts.use([
  TitleComponent, TooltipComponent, GridComponent, LegendComponent, GeoComponent, VisualMapComponent,
  BarChart, LineChart, ScatterChart, EffectScatterChart, HeatmapChart, CanvasRenderer
]);

export default {
  data() {
    return {
      currentTime: new Date().toLocaleTimeString(),
      incidents: [],
      policeForces: [],
      consoleMessages: [
        { id: 1, time: '10:31', content: '指令已发送至巡逻一队。' },
        { id: 2, time: '10:26', content: '交警二组已到达现场。' },
      ],
      allIncidents: [],
      todayIncidents: [],
      todayIncidentsCount: 0,
      todayIncidentsRate: 0,
      onlinePolice: 0,
      totalPolice: 0,
      averageResponseTime: 0,
      incidentHandlingRate: 0,
      incidentHandlingRateRate: 0,
      systemStatus: '正常运行',
      systemStatusColor: '#00ff00',
      onlineCommanders: 0,
      dataUpdateTime: new Date().toLocaleTimeString(),
      serverLoad: 45,
      mapChart: null,
      trendChart: null,
      mapCenter: [84.87, 45.49],
      mapZoom: 12,
      locateTargets: {
        center: [84.87, 45.49],
        headquarters: [116.4074, 39.9042],
      },
      currentLocateTarget: 'center',
      trendChartHeight: '250px',
      printTrendDataEnabled: true
    };
  },
  mounted() {
    this.startClock();
    this.fetchData();
    this.initMapChart();
    this.initTrendChart();
    this.fetchAllIncidents();
    this.fetchPoliceData();
    this.generateRandomTime();
    window.addEventListener('resize', this.handleResize);

    this.centerMap();

    this.startScrolling(this.$refs.incidentListScroll);
    this.startScrolling(this.$refs.policeForceScroll);
    this.startScrolling(this.$refs.consoleMessagesScroll);

    if (this.printTrendDataEnabled) {
      this.printTrendData();
    }
  },
  beforeUnmount() {
    if (this.clockInterval) {
      clearInterval(this.clockInterval);
    }
    window.removeEventListener('resize', this.handleResize);

    this.stopScrolling(this.$refs.incidentListScroll);
    this.stopScrolling(this.$refs.policeForceScroll);
    this.stopScrolling(this.$refs.consoleMessagesScroll);
  },
  methods: {
    initTrendChart() {
      const chartDom = document.getElementById('trend-chart-container');
      chartDom.style.height = this.trendChartHeight;
      this.trendChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: '#00c3ff',
          borderWidth: 1,
          textStyle: { color: '#fff' },
          axisPointer: {
            type: 'line',
            lineStyle: { color: '#00c3ff' }
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          containLabel: true,
          backgroundColor: 'rgba(0, 0, 0, 0.3)'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.getChartTimeLabels(),
          axisLine: {
            lineStyle: { color: '#00c3ff' },
            onZero: false
          },
          axisTick: { show: false },
          axisLabel: {
            textStyle: { color: '#999' },
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '警情数量',
          nameTextStyle: { color: '#00c3ff' },
          axisLine: {
            lineStyle: { color: '#00c3ff' },
            onZero: false
          },
          axisTick: { show: false },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 195, 255, 0.2)'
            }
          },
          axisLabel: {
            textStyle: { color: '#999' }
          }
        },
        series: [
          {
            name: '警情数量',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#00c3ff',
              borderColor: '#fff',
              borderWidth: 2
            },
            lineStyle: {
              color: '#00c3ff',
              width: 2
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(0, 195, 255, 0.4)' },
                { offset: 1, color: 'rgba(0, 195, 255, 0)' }
              ])
            },
            data: this.getIncidentTrendData()
          }
        ]
      };

      this.trendChart.setOption(option);
    },

    getChartTimeLabels() {
      const labels = [];
      for (let i = 0; i < 24; i += 4) {
        const hour = String(i).padStart(2, '0');
        labels.push(`${hour}:00`);
      }
      return labels;
    },

    getIncidentTrendData() {
      if (!this.allIncidents || this.allIncidents.length === 0) {
        return [0, 0, 0, 0, 0, 0];
      }

      const data = new Array(24).fill(0);
      this.allIncidents.forEach(incident => {
        const date = new Date(incident.reportTime);
        const hour = date.getHours();
        data[hour]++;
      });

      const groupedData = [];
      for (let i = 0; i < 24; i += 4) {
        const sum = data[i] + data[i+1] + data[i+2] + data[i+3];
        groupedData.push(sum);
      }

      return groupedData;
    },

    printTrendData() {
      const trendData = this.getIncidentTrendData();
      const timeLabels = this.getChartTimeLabels();

      console.log('========== 趋势图数据 ==========');
      console.log('时间点: ', timeLabels);
      console.log('警情数量: ', trendData);

      console.log('详细数据:');
      for (let i = 0; i < timeLabels.length; i++) {
        console.log(`${timeLabels[i]}: ${trendData[i]} 起警情`);
      }
      console.log('==============================');
    },

    updateTrendChart() {
      if (this.trendChart) {
        this.trendChart.setOption({
          series: [{
            data: this.getIncidentTrendData()
          }]
        });

        if (this.printTrendDataEnabled) {
          this.printTrendData();
        }
      }
    },
    calculateHandlingRate() {
      const completedIncidents = this.allIncidents.filter(
        incident => incident.incidentStatus === 'COMPLETED'
      );

      const totalCount = this.allIncidents.length;
      const completedCount = completedIncidents.length;

      this.incidentHandlingRate = totalCount > 0
        ? parseFloat(((completedCount / totalCount) * 100).toFixed(2))
        : 0;
    },
    generateRandomTime() {
      this.averageResponseTime = Math.random() * 4 + 1;
      this.averageResponseTime = this.averageResponseTime.toFixed(1);
    },
    async fetchPoliceData() {
      try {
        const response = await api.get('/officers');
        const policeList = response.data.data;

        this.totalPolice = policeList.length;
        this.onlinePolice = policeList.filter(
          item => item.statusDescription === '在岗'
        ).length;
      } catch (error) {
        console.error('获取警力数据失败：', error);
        this.onlinePolice = 0;
        this.totalPolice = 0;
      }
    },
    async fetchAllIncidents() {
      try {
        const response = await api.get('/incidents');
        this.allIncidents = response.data;
        this.filterTodayIncidents();
        this.calculateHandlingRate();
      } catch (error) {
        console.error('获取警情数据失败：', error);
        this.allIncidents = [];
        this.todayIncidents = [];
        this.todayIncidentsCount = 0;
        this.todayIncidentsRate = 0;
      }
    },
    filterTodayIncidents() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      const todayDateStr = `${year}-${month}-${day}`;

      this.todayIncidents = this.allIncidents.filter(incident => {
        const incidentDatePart = incident.reportTime.slice(0, 10);
        return incidentDatePart === todayDateStr;
      });

      this.todayIncidentsCount = this.todayIncidents.length;
      this.calculateRate();
    },
    calculateRate() {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      const yesterdayYear = yesterday.getFullYear();
      const yesterdayMonth = String(yesterday.getMonth() + 1).padStart(2, '0');
      const yesterdayDay = String(yesterday.getDate()).padStart(2, '0');
      const yesterdayDateStr = `${yesterdayYear}-${yesterdayMonth}-${yesterdayDay}`;

      const yesterdayIncidentsCount = this.allIncidents.filter(incident => {
        const incidentDatePart = incident.reportTime.slice(0, 10);
        return incidentDatePart === yesterdayDateStr;
      }).length;

      if (yesterdayIncidentsCount === 0) {
        this.todayIncidentsRate = this.todayIncidentsCount > 0 ? 100 : 0;
      } else {
        this.todayIncidentsRate = Math.round(
          ((this.todayIncidentsCount - yesterdayIncidentsCount) / yesterdayIncidentsCount) * 100
        );
      }
    },
    startClock() {
      this.clockInterval = setInterval(() => {
        this.currentTime = new Date().toLocaleTimeString('it-IT');
      }, 1000);
    },
    getRateColor(rate) {
      if (rate > 0) return 'rate-up';
      if (rate < 0) return 'rate-down';
      return '';
    },
    handleResize() {
      this.mapChart?.resize();
      this.trendChart?.resize();
    },
    initMapChart() {
      const chartDom = document.getElementById('main-map-container');
      this.mapChart = echarts.init(chartDom);
      const option = {
        tooltip: { trigger: 'item' },
        amap: {
          key: 'e67f0e9520643f148baa0e9747a27038',
          center: this.mapCenter,
          zoom: this.mapZoom,
          viewMode: '2D',
          mapStyle: 'amap://styles/white',
          echartsLayerZIndex: 2005,
        },
        series: [
          {
            name: '警力分布',
            type: 'effectScatter',
            coordinateSystem: 'amap',
            data: this.policeForces.map(force => ({ name: force.name, value: [force.longitude || 0, force.latitude || 0, 1] })),
            symbolSize: 15,
            showEffectOn: 'render',
            rippleEffect: { brushType: 'stroke' },
            itemStyle: { color: '#00c3ff' },
            label: { formatter: '{b}', position: 'right', show: true },
          },
          {
            name: '警情位置',
            type: 'scatter',
            coordinateSystem: 'amap',
            data: this.incidents.map(incident => ({ name: incident.incidentType, value: incident.coordinates })),
            symbolSize: 15,
            itemStyle: { color: '#ff5722' },
          }
        ]
      };
      this.mapChart.setOption(option);
    },
    async fetchData() {
      try {
        const incidentResponse = await api.get('/incidents');
        this.incidents = incidentResponse.data;

        const policeForceResponse = await api.get('/officers');
        this.policeForces = policeForceResponse.data.data;

        this.initMapChart();
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },
    centerMap(targetKey = null) {
      if (!this.mapChart || !this.mapChart.getModel().getComponent('amap')) {
        return;
      }

      const target = targetKey ? this.locateTargets[targetKey] : this.locateTargets[this.currentLocateTarget];

      if (targetKey) {
        this.currentLocateTarget = targetKey;
      }

      this.mapChart.dispatchAction({
        type: 'mapMove',
        mapType: 'amap',
        target: target,
        zoom: 14,
        animation: {
          duration: 1000,
          easing: 'cubicOut'
        }
      });

      this.showLocateTip(targetKey || this.currentLocateTarget);
    },
    showLocateTip(targetKey) {
      const targetNames = {
        center: '地图中心',
        headquarters: '指挥中心',
      };

      const tipName = targetNames[targetKey] || targetKey;

      this.mapChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: 0,
        position: 'insideBottom',
        formatter: `<div style="background:rgba(0,0,0,0.7); color:#fff; padding:5px; border-radius:3px;">
          已定位到：${tipName}
        </div>`
      });

      setTimeout(() => {
        this.mapChart.dispatchAction({
          type: 'hideTip'
        });
      }, 3000);
    },
    handleMapToolClick(toolType) {
      switch(toolType) {
        case 'zoom':
          console.log('缩放功能');
          break;
        case 'heatmap':
          console.log('热力图功能');
          break;
        case 'locate':
          const targets = Object.keys(this.locateTargets);
          const currentIndex = targets.indexOf(this.currentLocateTarget);
          const nextIndex = (currentIndex + 1) % targets.length;
          const nextTarget = targets[nextIndex];

          this.centerMap(nextTarget);
          break;
      }
    },
    startScrolling(element) {
      if (!element) return;
      element.scrollInterval = setInterval(() => {
        if (element.scrollTop + element.clientHeight >= element.scrollHeight) {
          element.scrollTop = 0;
        } else {
          element.scrollTop += 1;
        }
      }, 50);
    },
    stopScrolling(element) {
      if (element && element.scrollInterval) {
        clearInterval(element.scrollInterval);
      }
    }
  },
  watch: {
    allIncidents: {
      handler() {
        if (this.trendChart) {
          this.updateTrendChart();
        }
      },
      deep: true
    }
  }
};
</script>

<style scoped>
/* 引入基础样式 */
@import "@/assets/styles/views/CommandVisualization.css";

/* 趋势图容器样式 */
.chart-container {
  width: 100%;
  height: 100%;
  background-color: rgba(10, 20, 40, 0.6);
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 195, 255, 0.3);
  overflow: hidden;
}

.panel-title {
  color: #00c3ff;
  font-size: 18px;
  font-weight: bold;
  padding: 10px 15px;
  border-bottom: 1px solid rgba(0, 195, 255, 0.3);
  display: flex;
  align-items: center;
}

.panel-title i {
  margin-right: 8px;
  color: #00c3ff;
}

/* 趋势图数据打印区域样式 */
.trend-data-print {
  margin-top: 10px;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #00c3ff;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  font-size: 12px;
}

/* 新增样式：趋势图所在面板样式优化 */
.panel.statistics {
  overflow: hidden;
}

#trend-chart-container {
  width: 100%;
  height: inherit;
}
</style>
